import { ExportedResourceLibProps } from "@/components/ResourceLib"
import { useEditorContext } from "@/context/editContext"
import { FolderAddFilled, PlusCircleOutlined } from "@ant-design/icons"
import { styled, SxProps } from "@mui/material"
import { Badge, Button } from "antd"
import { BadgeProps } from "antd/lib"
import React, { useEffect, useState } from "react"
const StyledBadge = styled(Badge)(({ theme }) => ({}))
export interface useAppSourceOptions {}
export interface SourceBadgeProps extends BadgeProps, ExportedResourceLibProps {
  children?: any
  hidden?: boolean
  onOk?: (value: any) => void
  sx?: SxProps
}

const useAppSource = (options?: useAppSourceOptions) => {
  return [SourceBadge]
}

const SourceBadge = (props: SourceBadgeProps) => {
  const {
    children,
    offset,
    maxCount = 1,
    sourceTypes = ["IMAGE"],
    hidden = false,
    sx,
    style,
    onOk,
    ...otr
  } = props
  //当前是否在使用sourcelib获取数据
  const [actived, setActived] = useState(false)
  const [{ appSource }, dispatch] = useEditorContext()
  useEffect(() => {
    if (!appSource?.open && appSource?.value?.length > 0) {
      //获取值后关闭激活状态
      if (actived) {
        setActived(false)
        onOk && onOk(appSource?.value)
        dispatch({
          type: "updataAppSource",
          payload: { ...appSource, value: [] },
        })
      }
    }
  }, [appSource?.open])
  return !hidden ? (
    <StyledBadge
      status="default"
      offset={offset}
      style={style}
      sx={sx}
      count={
        <Button
          shape="circle"
          onClick={(e) => {
            e.stopPropagation()
            if (!appSource?.open) {
              setActived(true)
              dispatch({
                type: "updataAppSource",
                payload: {
                  open: true,
                  resourcesProps: {
                    maxCount,
                    sourceTypes,
                  },
                },
              })
            }
          }}
          icon={<FolderAddFilled></FolderAddFilled>}
        ></Button>
      }
    >
      {React.cloneElement(children, otr)}
    </StyledBadge>
  ) : (
    React.cloneElement(children, otr)
  )
}

export default useAppSource
